var express = require('express');
var conn = require('../public/javascripts/connect');
var crypto = require('crypto');
var router = express.Router();
router.get("/", function (req, res) {
    res.render('login', {login1: ""});
})
router.use("/", async function (req, res) {
    // console.log("1", req);
    // console.log("2", req.body);
    // console.log("3", JSON.parse(Object.keys(req.body)[0]));
    var md5 = crypto.createHash('md5');
    function md5fun(users) {
        crypto.createHash('md5');   //crypto模块功能是加密并生成各种散列,此处所示为MD5方式加密
        hash = md5.update(users.username + users.password).digest('hex');//加密后的密码
    }
    let users = JSON.parse(Object.keys(req.body)[0])
    console.log("users",users);
    let allowLogin = "", hash = "";
    let sql = `SELECT * FROM user WHERE  phone='${users.username}' AND user_pwd='${users.password}'`;
    console.log(sql);
    await new Promise(res => {
        conn.connection1.query(sql, function (err, result, fields) {
            if (err) {
                console.log('[SELECT ERROR1111] - ', err.message);
                return;
            }
            console.log("result", result);
            if (result != false) {
                md5fun(users);
                allowLogin = true;
                res(allowLogin)
            } else {
                allowLogin = false;
                res(allowLogin)
            }
        });
    })
    if (allowLogin) {
        let random = (Math.random() + "").split(".")[1];
        console.log(random);
        hash += "&" + random + "&12";
        console.log(hash);
        let sql1 = `UPDATE user SET sission='${hash}' WHERE phone='${users.username}' AND user_pwd='${users.password}'`;
        console.log(sql1);
        await new Promise(res => {
            conn.connection1.query(sql1, function (err, result, fields) {
                if (err) {
                    console.log('[Update ERROR] - ', err.message);
                    return;
                }
                console.log("更新", result);
                res(true)
            })
        })

        console.log(13513);
        res.cookie("jinshan_rabbing", hash, {maxAge: 3600 * 12 * 1000});
        console.log(456);

    }
    res.json({allowLogin: allowLogin, hash: hash});
})
module.exports = router;